﻿var normalm = L.tileLayer.chinaProvider('TianDiTu.Normal.Map', {
        maxZoom: 18,
        minZoom: 5
    }),
    normala = L.tileLayer.chinaProvider('TianDiTu.Normal.Annotion', {
        maxZoom: 18,
        minZoom: 5
    }),
    imgm = L.tileLayer.chinaProvider('TianDiTu.Satellite.Map', {
        maxZoom: 18,
        minZoom: 5
    }),
    imga = L.tileLayer.chinaProvider('TianDiTu.Satellite.Annotion', {
        maxZoom: 18,
        minZoom: 5
    });

var normal = L.layerGroup([normalm]),
    image = L.layerGroup([imgm]);

var baseLayers = {
    "地图": normal,
    "影像": image
}

var overlayLayers = {

}

var map = L.map("mapDiv", {
    zoominfoControl: false,
    positionControl:true,
    center: center,
    zoom: zoom,
    layers: [normal],
    zoomControl: false
});

L.control.layers(baseLayers, overlayLayers,{position:"bottomright",collapsed:true}).addTo(map);

var markerGroup = L.layerGroup([]).addTo(map);
//层级
L.control.zoom({position: 'topright'}).addTo(map);
//添加坐标位置
//L.control.mousePosition().addTo(map);
//地图比例尺
L.control.scale({position:"bottomleft",metric:true,imperial:false}).addTo(map);

var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);
// Set the title to show on the polygon button
L.drawLocal.draw.toolbar.buttons.polygon = '面查询';
L.drawLocal.draw.toolbar.buttons.rectangle = '矩形查询';
L.drawLocal.draw.toolbar.buttons.circle = '圆查询';

var drawControl = new L.Control.Draw({
    position: 'topright',
    draw: {
        polyline: false,
        polygon: true,
        rectangle: true,
        circle: true,
        marker: false,
        circlemarker:false
    },
    edit: {
        featureGroup: drawnItems,
        edit:false,
        remove: false
    }
});
map.addControl(drawControl);
var queryLayer;

map.on("moveend", function (e) {

    /*if(queryLayer.type == "circle"){
        var poly = turf.polygon(queryLayer.geometry.coordinates);
        var clipped = turf.bboxClip(poly, bbox);
    }*/
    if(drawnItems.getLayers().length > 0){
        var bounds = map.getBounds();
        var bbox = JSON.parse("["+bounds.toBBoxString()+"]");
        var feature = drawnItems.getLayers()[0];
        if (feature.type === 'polygon') {
            var poly = turf.polygon(feature.toGeoJSON().geometry.coordinates);
            var clipped = turf.bboxClip(poly, bbox);
            if(clipped.geometry.coordinates.length == 1){
                var clippedLayer = L.geoJson({features:[clipped]},{
                    coordsToLatLngs: function coordsToLatLngs(f){
                        return [f[1], f[0]];
                    }
                });
                var geoJsonStr = JSON.stringify(clippedLayer.getLayers()[0]._latlngs[0]);
                var addressStr = $("#searchText").val();
                clearLayerMoveEnd();
                getGeometryPolygonQuery(addressStr ,geoJsonStr)
            }
        }
        if (feature.type === 'rectangle') {
            var poly = turf.polygon(feature.toGeoJSON().geometry.coordinates);
            var clipped = turf.bboxClip(poly, bbox);
            if(clipped.geometry.coordinates.length == 1){
                var clippedLayer = L.geoJson({features:[clipped]},{
                    coordsToLatLngs: function coordsToLatLngs(f){
                        return [f[1], f[0]];
                    }
                });
                var geoJsonStr = JSON.stringify(clippedLayer.getBounds());
                var addressStr = $("#searchText").val();
                clearLayerMoveEnd();
                getGeometryRectangleQuery(addressStr ,geoJsonStr)
            }
           /* var addressStr = $("#searchText").val();
            var geoJsonStr = JSON.stringify(feature._bounds);
            getGeometryRectangleQuery(addressStr ,geoJsonStr)*/
        }
    }else{
        clearLayerMoveEnd();
        var bounds = map.getBounds();
        var geoJsonStr = JSON.stringify(bounds);
        var addressStr = $("#searchText").val();
        getGeometryRectangleQuery(addressStr ,geoJsonStr)
    }
    //
});



map.on(L.Draw.Event.CREATED, function (e) {
    clearLayers();
    var geoType = e.layerType,
        queryLayer = e.layer;
    queryLayer.type = geoType;
    if (geoType === 'polygon') {
        var addressStr = $("#searchText").val();
        var geoJsonStr = JSON.stringify(queryLayer._latlngs[0]);
        getGeometryPolygonQuery(addressStr ,geoJsonStr)
    }
    if (geoType === 'rectangle') {
        var addressStr = $("#searchText").val();
        var geoJsonStr = JSON.stringify(queryLayer._bounds);
        getGeometryRectangleQuery(addressStr ,geoJsonStr)
    }
    if (geoType === 'circle') {
        var addressStr = $("#searchText").val();
        var geoJsonStr = JSON.stringify(queryLayer.getLatLng());
        var radius = queryLayer.getRadius();
        getGeometryCircleQuery(addressStr ,geoJsonStr,radius)
    }
    drawnItems.addLayer(queryLayer);
});


function getGeometryPolygonQuery(address,geoJsonStr) {
    var url = encodeURI("./address/getGeometryPolygonQuery?address=" + address+"&geoJson="+geoJsonStr+"&zoom=" + map.getZoom());
    $.get(url,function(data,status){
        if(isNull(data)) return;
        data = JSON.parse(data);
        if(data.length>0){
            addMarkers(data);
        }
    });
}

function getGeometryRectangleQuery(address,geoJsonStr) {
    var zoom = map.getZoom() + 1;
    var url =encodeURI("./address/getGeometryRectangleQuery?address=" + address+"&geoJson="+geoJsonStr+"&zoom="+zoom);
    $.get(url,function(data,status){
        if(isNull(data)) return;
        data = JSON.parse(data);
        if(data.length>0){
            addMarkers(data);
        }
    });
}

function getGeometryCircleQuery(address,geoJsonStr,radius) {
    var url =encodeURI("./address/getGeometryCircleQuery?address=" + address + "&geoJson=" + geoJsonStr + "&radius=" + radius);
    $.get(url,function(data,status){
        if(isNull(data)) return;
        data = JSON.parse(data);
        if(data.length>0){
            addMarkerCluster(data);
        }
    });
}

var progress = document.getElementById('progress');
var progressBar = document.getElementById('progress-bar');

function updateProgressBar(processed, total, elapsed, layersArray) {
    if (elapsed > 1000) {
        // if it takes more than a second to load, display the progress bar:
        progress.style.display = 'block';
        progressBar.style.width = Math.round(processed/total*100) + '%';
    }
    if (processed === total) {
        // all markers processed - hide the progress bar:
        progress.style.display = 'none';
    }
}

function addMarkerCluster(data) {
    var markers = L.markerClusterGroup({ spiderfyOnMaxZoom: true,chunkedLoading: true, chunkProgress: updateProgressBar });
    var markerList = [];
    console.log('start creating markers: ' + window.performance.now());
    for (var i = 0; i < data.length; i++) {
        var row =  data[i];
        if(isNotNull(row.jd)&&isNotNull(row.wd)&&isNotNull(row.dzmc)){
            var marker = L.marker([row.wd,row.jd]);
            marker.bindPopup(row.dzmc, {
                pane: "popupPane",
                permanent: true,
                opacity: 0.9
            });
            markerList.push(marker);
        }
    }
    console.log('start clustering: ' + window.performance.now());
    markers.addLayers(markerList);
    markerGroup.addLayer(markers);
}
var iconSize = [10,10];
var icon = L.divIcon({ className: "dist-marker", html: "", iconSize: iconSize });
function addMarkers(data) {
    for(var i = 0; i < data.length; i++ ){
        var row =  data[i];
        if(isNotNull(row.JDWDZB.lat)&&isNotNull(row.JDWDZB.lat)&&isNotNull(row.DZYSLJ)){
            var marker = L.marker([row.JDWDZB.lat,row.JDWDZB.lon], { title: row.DZYSLJ, icon: icon });
            marker.bindPopup(row.DZYSLJ, {
                pane: "popupPane",
                permanent: true,
                opacity: 0.9
            });
            markerGroup.addLayer(marker);
            markers.push(marker);
        }
    }
}

map.on(L.Draw.Event.EDITED, function (e) {
    var layers = e.layers;
    var countOfEditedLayers = 0;
    layers.eachLayer(function (layer) {
        countOfEditedLayers++;
    });
    console.log("Edited " + countOfEditedLayers + " layers");
});

map.on(L.Draw.Event.CREATED, function (e) {

})

var marker;     //marker点
var markers=[]; //标注组
//地址元素添加Marker
function showMarker(lat,lng){
    clearLayers();
    //注册点击事件（点击定位）
    map.on('click', function(e) {
        if(marker!=undefined){
            map.removeLayer(marker);
        }
        lng = e.latlng.lng;
        lat = e.latlng.lat;
        marker = L.marker([lat,lng]);
        markerGroup.addLayer(marker);
        $("#lng").val(lng.toFixed(6)).trigger('change');
        $("#lat").val(lat.toFixed(6)).trigger('change');
        markers.push(marker);
    });
    //如果传来经纬度则通过经纬度定位
    if(lat!=""&&lat!=undefined&&lng!=""&&lng!=undefined){
        marker = L.marker([lat,lng]);
        markerGroup.addLayer(marker);
        map.panTo([lat,lng]);
    }
    if(marker!=undefined){
        markers.push(marker);
    }
}
//删除方法
function removeMarkers(){
    if(markers!=undefined && markers!=null){
        for (var i=0 ;i<markers.length;i++){
            map.removeLayer(markers[i]);
        }
    }
    markers = [];
}

//清楚地图上所有的点
function clearLayerMoveEnd(){
    markerGroup.clearLayers();
    markers = [];
}

//清楚地图上所有的点
function clearLayers(){
    drawnItems.clearLayers();
    markerGroup.clearLayers();
    markers = [];
}
$(function () {
    clearLayerMoveEnd();
    var bounds = map.getBounds();
    var geoJsonStr = JSON.stringify(bounds);
    var addressStr = $("#searchText").val();
    getGeometryRectangleQuery(addressStr ,geoJsonStr);
});